const api = require('../../../api/mop_api');
import { toast, log, err, back } from '../../../utils/wxapi';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    sort: '',
    name: '',
    // 点击编辑菜品拿到传过来的id
    id: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id: options.id,
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    const { id } = this.data;
    try {
      if (id) {
        const { respCode, source, msg } = await api.typeget({ id });
        if (respCode === 200) {
          const { name, sort } = JSON.parse(source);
          this.setData({ name, sort });
        } else {
          err(msg);
        }
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  // 修改列表信息
  async typeput() {
    const { id, name, sort } = this.data;
    try {
      const { respCode, msg } = await api.typeput({ id, name, sort });
      if (respCode === 200) {
        toast('修改成功,即将跳转');
        back();
      } else {
        toast(msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  async posttype() {
    const { name, sort } = this.data;
    try {
      if (!name || !sort) {
        return toast('请将页面信息填写完整');
      }
      const { respCode, msg } = await api.newtype({ name, sort });
      if (respCode === 200) {
        toast('添加成功');
        back();
      } else {
        toast(msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
});
